# Maintainer: Alexander Epaneshnikov <alex19ep@archlinux.com>
# Contributor: libertylocked <libertylocked@disroot.org>

pkgname=bitwarden-cli
pkgver=2023.10.0
pkgrel=1
pkgdesc="The command line vault"
arch=('loong64' 'x86_64')
url="https://github.com/bitwarden/clients"
license=('GPL3')
depends=('nodejs-lts-hydrogen')
makedepends=('git' 'npm' 'modclean')
options=(!emptydirs)
source=(bitwarden::git+https://github.com/bitwarden/clients.git#tag=cli-v${pkgver})
sha512sums=('SKIP')

prepare() {
	cd bitwarden

	export npm_config_build_from_source=true
	export npm_config_cache="$srcdir/npm_cache"

	npm ci
}

build() {
	cd bitwarden/apps/cli
	export npm_config_cache="$srcdir/npm_cache"
	npm run dist:lin
	npm run clean
	node ./build/bw.js completion --shell zsh > _bw
}

package() {
	cd bitwarden/apps/cli
	npm install --production -g --prefix "$pkgdir"/usr $(npm pack . | tail -1)

	# Non-deterministic race in npm gives 777 permissions to random directories.
	# See https://github.com/npm/npm/issues/9359 for details.
	chmod -R u=rwX,go=rX "$pkgdir"
	# npm gives ownership of ALL FILES to build user
	# https://bugs.archlinux.org/task/63396
	chown -R root:root "${pkgdir}"

	# package zsh completions
	install -vDm644 _bw -t "${pkgdir}/usr/share/zsh/site-functions"

	# cleanup
	sed -e "s|${srcdir}|/|" -i "$pkgdir"/usr/lib/node_modules/@bitwarden/cli/package.json
	find "$pkgdir"/usr/lib/node_modules -name 'package.json' -exec sed -e "s|${srcdir}||" -i {} \;
	modclean --path "$pkgdir"/usr/lib -r -a "*.ts,.bin,.github,.vscode,bin.js" --ignore='license'
}
